<?php
/**
 * @author extintor
 * @copyright 2012
 */


class iWork{

    public $sessionUp;
    private $curl;
    private $host;
    private $user;
    private $password;
    private $lastId;
    private $lastZipUrl;

    public function __construct($host,$user,$password){
        $this->curl=new cURL();
        $this->host=$host;
        $this->user=$user;
        $this->password=$password;
        
        //Try to log in the system
        $this->login();
    }

    private function login (){
        if (!$this->sessionUp){
            //[viewstate], [eventvalidation], [user], [password]        
            $data="ctl00%24srcScriptManager=ctl00%24pnlUpdate%7Cctl00%24cphContent%24btEnviar&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=[viewstate]&__EVENTVALIDATION=[eventvalidation]&ctl00%24cphContent%24txtUserId=[user]&ctl00%24cphContent%24ajax_valUserId_ClientState=&ctl00%24cphContent%24txtPassword=[password]&ctl00%24cphContent%24ajax_valPassword_ClientState=&__ASYNCPOST=true&ctl00%24cphContent%24btEnviar=Enviar";
        
            //Get login page data to retrieve session variables
            $html=$this->curl->get("http://".$this->host."/Manager/Login.aspx");
            
            //extract session variables
            $parser=new DOMDocument();        
            $parser->loadHTML($html);
            
            $viewstate=$parser->getElementById("__VIEWSTATE")->getAttributeNode("value")->value;
            $eventvalidation=$parser->getElementById("__EVENTVALIDATION")->getAttributeNode("value")->value;
            
            //Insert session variables in data
            $data=str_replace("[viewstate]",urlencode($viewstate),$data);
            $data=str_replace("[eventvalidation]",urlencode($eventvalidation),$data);
            $data=str_replace("[user]",$this->user,$data);
            $data=str_replace("[password]",$this->password,$data);
    
            //Post data
            $html=$this->curl->post("http://".$this->host."/Manager/Login.aspx",$data);
            
            //Check for correct login
            if(strpos($html,"Manager/Index_MisTareas.aspx"))
               $this->sessionUp=true;
            else
               $this->sessionUp=false; 
        }
    }

    public function getTaskDetail($taskId){
        //Exit if don't have a valid session
        if (!$this->sessionUp)
           return "Session not established correctly";
        
        $html=$this->curl->get("http://".$this->host."/Manager/Edit_Tarea.aspx?IdTarea=".$taskId);
        //Return an XML with error if so
        if(strpos($html,"Runtime Error"))
          return "<xml><error><taskId>".$taskId."</taskId><description>Error retrieving task with id=".$taskId."</description></error></xml>";

        //extract session variables
        $parser=new DOMDocument();        
        $parser->loadHTML($html);
        
        $xml='';
        $xml.='<iWorkTask id='.$taskId.'>';
        $xml.='<elemento>';
        $xml.='<producto>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtProducto")->nodeValue.'</producto>';
        $xml.='<avid>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtContratoAVID")->nodeValue.'</avid>';
        $xml.='<contrato>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtContratoProducto")->nodeValue.'</contrato>';
        $xml.='<referencia>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtRefAnuncio")->nodeValue.'</referencia>';
        $xml.='<tarea>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtTareaWorkFlow")->nodeValue.'</tarea>';
        $xml.='<estado>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtEstado")->nodeValue.'</estado>';
        $xml.='</elemento>';
        $xml.='<comercial>';
        $xml.='<id>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtCodVendedor")->nodeValue.'</id>';
        $xml.='<nombre>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtVendedor_Nombre")->nodeValue.'</nombre>';
        $xml.='<email>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtVendedor_EMail")->nodeValue.'</email>';
        $xml.='<telefono>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtVendedor_Telefono")->nodeValue.'</telefono>';
        $xml.='<movil>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtVendedor_Movil")->nodeValue.'</movil>';
        $xml.='</comercial>';
        $xml.='<cliente>';
        $xml.='<id>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtCodCliente")->nodeValue.'</id>';
        $xml.='<nombre>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtCliente_Nombre")->nodeValue.'</nombre>';
        $xml.='<contacto>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtCliente_PersonaContacto")->nodeValue.'</contacto>';
        $xml.='<email>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtCliente_EMail")->nodeValue.'</email>';
        $xml.='<telefono>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_txtCliente_Telefono")->nodeValue.'</telefono>';
        $xml.='<url>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_lnkCliente_Url")->nodeValue.'</url>';
        $xml.='</cliente>';
        $xml.='<urlzip>'.$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_lnkAnexos")->getAttributeNode("href")->value.'</urlzip>';
        $xml.='</iWorkTask>';
        
        //$xml="<pre>".str_replace("<","&lt;",str_replace(">","&gt;",$xml))."</pre>";
        $this->lastId=$taskId;
        $this->lastZipUrl=$parser->getElementById("ctl00_cphToolBar_ctrlCabeceraTarea_lnkAnexos")->getAttributeNode("href")->value;
        
        return $xml;   
    }
    public function getTaskZip($taskId){
        //Exit if don't have a valid session
        if (!$this->sessionUp)
           return "Session not established correctly";
        
        //Is the last downloaded task? If not, download it first
        if($taskId!=$this->lastId)
          $this->getTaskDetail($taskId);
        
        $zip=$this->curl->get("http://".$this->host."/Manager/".$this->lastZipUrl);
        return $zip;
    }    
}

?>